import React, { useEffect, useState, useRef } from 'react';
import { InputItem, List, Picker, Button, TextareaItem, Modal, Toast } from "antd-mobile";
import { createForm } from 'rc-form';
import { commonReq } from 'dcloud-core';
import { httpUtil } from 'dcloud-utils';
import { httpUrl } from 'dcloud-core';
import Router from "umi/router";


// 全局防止反复提交时间；
const WAITING = 120;
const Page = (props) => {
    // 有多少个兑换码
    const [key, setKey] = useState('-');
    // 每个兑换号可以兑换多少口罩
    const [count, setCount] = useState('-');
    // 是否禁用提交按钮（兑换号为 0 或 120秒内重复提交）
    const [disabled, setDisabled] = useState(false);
    const [waiting, setWaiting] = useState(WAITING);
    // 选中的自提点地址（用于回显地址信息）
    const [placeId, setPlaceId] = useState(null);
    const [place, setPlace] = useState(null);
    // 是否显示或必填地址
    const [addressStatus, setAddressStatus] = useState();
    const [addressIsShow, setAddressIsShow] = useState();
    // 返回结果
    const [modal, setModal] = useState(false);
    const [modalMsg, setModalMsg] = useState('系统已收到您的预约申请，请耐心等待预约结果。');
    const [seasons, setSeasons] = useState([]);
    const [myVar, setmyVar] = useState(null);
    // 表单使用
    const { getFieldProps, getFieldError } = props.form;
    const placeRef = useRef();

    // phone 
    const [phone, setPhone] = useState(localStorage.getItem("userPhone"));
    useEffect(() => {
        const tenantId = localStorage.getItem("tenantId");
        httpUtil.get(httpUrl.getAppointmentBeforeInfo, { tenantId: tenantId }).then((res) => {
          if (res.code == 200) {
            setPhone(res.data.mobilePhone);
            setKey(res.data.appointmentNoNumber);
            setCount(res.data.proportion);
            // 是否必填用户地址
            setAddressStatus(res.data.addressStatus);
            // 是否显示用户地址
            setAddressIsShow(res.data.addressIsShow);
          }
          console.log(res);
        })

        // 获取地区列表
        httpUtil.get(httpUrl.list, {
            tenantId: tenantId
        }).then((data) => {
            data.data.forEach((item) => {
                seasons.push(
                    {
                        label: item.siteName,
                        value: item.id,
                        place: item.siteAddress,
                        stock: item.stock
                    }
                )
            })
            setSeasons(seasons);
        }).catch((error) => {

        })

        const time = getWaitingTime();
        if (time && time != 0 && time != WAITING) {
            initWaitingTime();
        } else
            localStorage.setItem("time", WAITING);
    }, [])

    useEffect(() => {
        console.log(placeRef.current);
        placeRef.current.focus();
    }, [place])

    /**
     * 提交
     */
    const onSubmit = () => {
        props.form.validateFields({ force: true }, (error) => {
            if (!error) {
                const params = Object.assign({}, props.form.getFieldsValue());
                if(place.stock <= 0){
                    Toast.offline('很抱歉，当前自提点已经没有库存了！', 1);
                    return;
                }
                /**
                 * 需要提交的字段
                 */
                const tenantId = localStorage.getItem("tenantId");
                httpUtil.post(httpUrl.order, {
                    proportion: count, //proportion
                    appointmentNoNumber: key, //appointmentNoNumber
                    identityNo: params.number,
                    mobilePhone: params.phone,
                    name: params.userName,
                    selfSubmitId: params.place[0],
                    address: params.address,
                    tenantId: tenantId
                }).then((data) => {
                    if (data.code === 200) {
                        // modalMsg = data.msg;
                        setModal(true);
                    } else {
                        Toast.offline(data.msg, 1);
                    }
                    console.log(data);
                }).catch((error) => {

                })
                initWaitingTime();
            } else {
                Toast.offline('请正确填写信息..', 1);
            }
        });
    }

    const getWaitingTime = () => {
        const time = localStorage.getItem("time");
        if (time)
            return parseInt(time);
        else
            return 0
    }

    /** 全局防反复提交 */
    const initWaitingTime = () => {
        setDisabled(true);
        if (getWaitingTime() === 0) {
            localStorage.setItem("time", WAITING);
            setWaiting(WAITING);
        }
        if (!myVar) {
            setmyVar(true);
            let _myVar = setInterval(() => {
                let time = getWaitingTime();
                if (time === 0) {
                    setmyVar(false);
                    setDisabled(false);
                    clearInterval(_myVar);
                } else {
                    time--;
                    localStorage.setItem("time", time);
                    setWaiting(time);
                }
            }, 1000);
        }

    }

    /** 验证手机号 */
    const testPhone = (rule, value, callback) => {
        commonReq.mobile(value, '').then((_value) => {
            callback();
        }).catch((e) => {
            callback(e);
        });
    }

    /** 验证姓名 */
    const testName = (rule, value, callback) => {
        commonReq.cnName(value, '中文名不能为空').then((_value) => {
            callback();
        }).catch((e) => {
            callback(e);
        });
    }

    /** 身份证 */
    const testIdCard = (rule, value, callback) => {
        commonReq.idCard(value, '中文名不能为空').then((_value) => {
            callback();
        }).catch((e) => {
            callback(e);
        });
    }

    /**
     * 表单提交页面
     */
    return (
        <div>
            <Modal
                visible={modal}
                transparent
                maskClosable={false}
                title="系统提示"
                footer={[{ text: '返回', onPress: () => { Router.replace('/main') } }]}
            >
                <div style={{ height: 100, overflow: 'scroll' }}>
                    {modalMsg}
                </div>
            </Modal>
            <List renderHeader={() => '请输入预约信息'}>
                <List.Item >
                    {/* <InputItem
                        value={key}
                        editable={false}
                    >预约号</InputItem> */}
                    <InputItem value={(parseInt(key) * parseInt(count))}
                        editable={false}
                        extra="个口罩（总计）"
                    >可预约</InputItem>
                    <InputItem
                        type="text"
                        {...getFieldProps('userName', {
                            initialValue: '',
                            rules: [{
                                required: true, message: '姓名不能为空'
                            }, {
                                validator: testName
                            }],
                            // validateTrigger: 'onSubmit'
                        })}
                        error={!!getFieldError('userName')}
                        clear
                        placeholder="请输入您的姓名"
                        maxLength={6}
                    >姓名</InputItem>
                    <InputItem
                        type={'number'}
                        {...getFieldProps('phone', {
                            initialValue: phone,
                            rules: [{
                                required: true, message: '手机号不能为空'
                            }, {
                                validator: testPhone
                            }],
                            // validateTrigger: 'onSubmit'
                        })}
                        error={!!getFieldError('phone')}
                        clear
                        maxLength={11}
                        placeholder="请输入您的手机号"
                    >手机号</InputItem>
                    <InputItem
                        {...getFieldProps('number', {
                            initialValue: '',
                            rules: [{
                                required: true, message: '身份证号不能为空'
                            }, {
                                validator: testIdCard
                            }],
                            // validateTrigger: 'onSubmit'
                        })}
                        error={!!getFieldError('number')}
                        clear
                        placeholder="请输入您的身份证号"
                        maxLength={18}
                    >身份证号</InputItem>
                    {
                        addressIsShow == "0"?    <TextareaItem
                        autoHeight={true}
                        minLength={5}
                        maxLength={60}
                        title="地址"
                        error={!!getFieldError('address')}
                        {...getFieldProps('address', {
                            initialValue: '',
                            rules: [{
                                required: addressStatus == "0" ? true : false, message: '地址不能为空'
                            }],
                        })}
                    />: null
                    }
                </List.Item>
            </List>
            <List renderHeader={() => '请选择自提点'}>
                <List.Item error={!!getFieldError('place')} >
                    <Picker
                        data={seasons}
                        title="自提点"
                        extra="请选择自提点"
                        cols={1}
                        {...getFieldProps('place', {
                            initialValue: '',
                            rules: [{
                                required: true, message: '自提点不能为空'
                            }],
                            // validateTrigger: 'onSubmit'
                        })}
                        onOk={(v) => {
                            if (seasons.length > 0)
                                for (let i = 0, len = seasons.length; i < len; i++) {
                                    if (v[0] === seasons[i].value) {
                                        setPlace(seasons[i]);
                                        return;
                                    }
                                }
                            setPlaceId(v[0]);
                        }}
                    >
                        <List.Item arrow="horizontal">自提点</List.Item>
                    </Picker>
                    <TextareaItem
                        ref={placeRef}
                        autoHeight={true}
                        title="自提点地址"
                        editable={false}
                        value={place? place.place : ''}
                    />
                    <TextareaItem
                        autoHeight={true}
                        title="剩余口罩数量"
                        editable={false}
                        value={place? place.stock.toString() : ''}
                    />
                </List.Item>
            </List>
            <List.Item>
                <Button type="primary" disabled={disabled} activeStyle={{ opacity: .8, backgroundColor: '#e7572f' }} style={{ fontSize: '14px', height: '44px', lineHeight: '44px' }} onClick={() => { onSubmit() }}>
                    {disabled ? `请等待 ${waiting} 秒后再试` : '提交预约信息'}
                </Button>
            </List.Item>
        </div>
    )
}

const H5Page = createForm()(Page);
export default H5Page;